using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.Xml;

namespace Umdf.SideShow.Scf.ObjectModel
{
    public enum MenuSelectAction
    {
        [XmlEnum("target")]
        Target,
        [XmlEnum("menuid")]
        MenuId
    }

    public class ScfMenu : ScfBodyElement
    {
        private MenuSelectAction _selectAction;
        private List<ScfObject> _children;

        public MenuSelectAction SelectAction
        {
            get { return _selectAction; }
            set { _selectAction = value; }
        }

        public List<ScfObject> Children
        {
            get
            {
                if (_children == null)
                {
                    _children = new List<ScfObject>();
                }
                return _children;
            }
        }

        protected internal override void DeserializeFromXml(System.Xml.XmlNode node)
        {
            base.DeserializeFromXml(node);
            _selectAction = GetAttribute<MenuSelectAction>(node, "selectaction");
            foreach (XmlNode child in node.ChildNodes)
            {
                ScfObject childObject = null;
                switch (child.LocalName)
                {
                    case "item":
                        childObject = new ScfMenuItem();
                        break;
                    case "div":
                        childObject = new ScfDivider();
                        break;
                    case "btn":
                        childObject = new ScfButton();
                        break;
                }
                if (childObject != null)
                {
                    childObject.DeserializeFromXml(child);
                    Children.Add(childObject);
                }
            }
        }

        protected internal override void SerializeObject(System.IO.BinaryWriter writer)
        {
            base.SerializeObject(writer);
            writer.Write((int)_selectAction);
            writer.Write(Children.Count);
            foreach (ScfObject o in Children)
            {
                writer.Write(o.GetType().FullName);
                o.SerializeObject(writer);
            }
        }

        protected internal override void DeserializeObject(System.IO.BinaryReader reader)
        {
            base.DeserializeObject(reader);
            _selectAction = (MenuSelectAction)reader.ReadInt32();
            int count = reader.ReadInt32();
            _children = new List<ScfObject>();
            for (int i = 0; i < count; i++)
            {
                string typeName = reader.ReadString();
                Type t = Type.GetType(typeName);
                ScfObject c = (ScfObject)Activator.CreateInstance(t);
                c.DeserializeObject(reader);
                _children.Add(c);
            }
        }
    }
}
